<template>
  <view>
    <!-- 添加隐藏的 canvas 组件 -->
    <canvas
      canvas-id="watermark-canvas"
      :style="{ width: canvasWidth, height: canvasHeight, position: 'absolute', top: '-9999px' }"
    ></canvas>

    <wd-upload
      :file-list="fileList"
      image-mode="aspectFill"
      :action="action"
      @change="handleChange"
      :before-upload="beforeUpload"
      :before-choose="beforeChoose"
    ></wd-upload>
  </view>
</template>

<script lang="ts" setup>
import { ref, defineProps, defineEmits } from 'vue'
const props = defineProps<{
  modelValue: any[]
}>()

const emit = defineEmits(['update:modelValue'])
const fileList = ref(props.modelValue)
const action: string = 'https://mockapi.eolink.com/zhTuw2P8c29bc981a741931bdd86eb04dc1e8fd64865cb5/upload'
const canvasWidth = ref('')
const canvasHeight = ref('')
const { proxy } = getCurrentInstance()

function handleChange({ fileList: files }) {
  fileList.value = files
  emit('update:modelValue', fileList.value)
  console.log(fileList.value, 666)
}
const beforeChoose = async ({ fileList, resolve }) => {
  console.log(fileList, 5555)
}
const beforeUpload = async ({ files, resolve }) => {
  // uni.getLocation({
  //   type: 'gcj02', // 坐标系类型，gcj02为国测局坐标（适用于高德、腾讯等地图）
  //   geocode: true,
  //   success: res => {
  //     console.log('当前位置的经度:', res.longitude)
  //     console.log('当前位置的纬度:', res.latitude)
  //     console.log(res, 666)

  //     // 获取到经纬度后，进行逆地理编码
  //     //   this.reverseGeocode(res.longitude, res.latitude)
  //   },
  //   fail: err => {
  //     console.error('获取定位失败:', err)
  //     // 处理定位失败逻辑，例如提示用户开启定位权限
  //     uni.showToast({
  //       title: '获取位置信息失败，请检查定位权限',
  //       icon: 'none'
  //     })
  //   }
  // })
  for (let index = 0; index < files.length; index++) {
    const file = files[index]
    try {
      const imagePath = await addWatermark(file.path)
      files[index].path = imagePath

      // 这里可以处理添加水印后的图片路径
    } catch (error) {
      console.error('添加水印失败:', error)
    }
  }

  resolve(true)
}

const addWatermark = (tempFilePath: string): Promise<string> => {
  return new Promise((resolve, reject) => {
    uni.getImageInfo({
      src: tempFilePath,
      success: async res => {
        canvasWidth.value = `${res.width}px`
        canvasHeight.value = `${res.height}px`

        const ctx = uni.createCanvasContext('watermark-canvas', proxy)
        ctx.clearRect(0, 0, res.width, res.height)

        // 绘制原图
        ctx.drawImage(tempFilePath, 0, 0, res.width, res.height)
        await new Promise(resolve => {
          setTimeout(() => {
            resolve(true)
          }, 100)
        })
        // 设置全局样式
        const padding = 20 // 基础边距
        const lineHeight = 36 // 行高
        const maxWidth = 450 // 最大文本宽度

        // 计算内容总高度
        const content = [
          { label: '项目名称：', value: '项目名称：' },
          { label: '拍摄时间：', value: '2025.04.10 16:40' },
          { label: '拍摄账号：', value: '新亚洲' },
          { label: '拍摄地址：', value: ['江苏省苏州市太仓', '市娄东街道大连东路70'] }
        ]

        let totalHeight = 0
        content.forEach(item => {
          totalHeight += Array.isArray(item.value) ? lineHeight * item.value.length + 10 : lineHeight + 10
        })

        // 计算起始位置（左下角）
        let startY = res.height - totalHeight - padding * 2
        ctx.fillStyle = 'rgba(38, 178, 243, 0.6)'
        ctx.fillRect(padding, startY - 2 * padding - 80, maxWidth, 80)
        ctx.font = '26px "Microsoft YaHei"'
        ctx.fillStyle = '#ffffff'
        ctx.fillText('项目名称', maxWidth / 2 - 20, startY - 2 * padding - 30)
        // 绘制半透明背景
        ctx.fillStyle = 'rgba(0, 0, 0, 0.6)'
        ctx.fillRect(padding, startY - 2 * padding, maxWidth, totalHeight + padding * 2)

        // 设置文字样式
        ctx.font = '24px "Microsoft YaHei"'
        ctx.fillStyle = '#ffffff'
        // ctx.textBaseline = 'top'

        // 绘制内容项
        content.forEach(item => {
          // 绘制标签
          ctx.fillStyle = '#ffd700'
          const labelX = padding + 20
          const labelY = startY
          ctx.fillText(item.label, labelX, labelY, 150)

          // 绘制值
          ctx.fillStyle = '#ffffff'
          const valueX = 160

          if (Array.isArray(item.value)) {
            item.value.forEach((line, index) => {
              ctx.fillText(line, valueX, startY + index * lineHeight, maxWidth - 160)
            })
            startY += lineHeight * item.value.length
          } else {
            ctx.fillText(item.value, valueX, startY, maxWidth - 160)
            startY += lineHeight
          }

          startY += 10 // 段间距
        })

        // 绘制装饰边框
        // ctx.strokeStyle = 'rgba(255, 215, 0, 0.8)'
        // ctx.lineWidth = 2
        // ctx.strokeRect(
        //   padding,
        //   res.height - totalHeight - padding * 2,
        //   res.width - padding * 2,
        //   totalHeight + padding * 2
        // )

        // 生成图片
        ctx.draw(true, () => {
          uni.canvasToTempFilePath(
            {
              canvasId: 'watermark-canvas',
              destWidth: res.width,
              destHeight: res.height,
              fileType: 'jpg',
              quality: 0.8,
              success: fileRes => {
                resolve(fileRes.tempFilePath)
              },
              fail: reject
            },
            proxy
          )
        })
      },
      fail: reject
    })
  })
}
</script>
